/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dungeonsolver.controller;

import dungeonsolver.controller.algorithm.IAlgorithm;
import dungeonsolver.helper.AlgorithmFactory;
import dungeonsolver.helper.Utility;
import dungeonsolver.model.Labyrinth;
import java.awt.Point;
import java.util.Arrays;
import java.util.Vector;

/**
 *
 * @author LegACy
 */
public class PathFinder {
	public PathFinder(String file) {
		//Create labyrinth
		m_Labyrinth = new Labyrinth(file);

		//Initialize path
		m_Path = null;
	}

	public void calculatePath(String algorithm) {
		//Create path
		m_Path = new Vector<Point>();

		//Create algorithm
		IAlgorithm Algorithm = AlgorithmFactory.createAlgorithm(algorithm);
		if (Algorithm == null) return;

		//Log
		Utility.instance().addLog("Using " + algorithm + " algorithm for pathfinding.");
		Utility.instance().addLog("");

		//Get starting point
		Point Start = m_Labyrinth.getEntry();
		m_Path.add(Start);

		//For each button
		for (int i = 0; i < m_Labyrinth.getButtons().length; i++) {
			//Log 
			String Log	 = "Calculating path from [" + Start.x + "," + Start.y + "] to [";
			Log			+= m_Labyrinth.getButtons()[i].x + "," + m_Labyrinth.getButtons()[i].y + "]...";
			Utility.instance().addLog(Log);

			//Get sub path
			Point[] SubPath = Algorithm.getPath(m_Labyrinth, Start, m_Labyrinth.getButtons()[i]);
			m_Path.addAll(Arrays.asList(SubPath));

			//Set as starting point
			Start = m_Path.lastElement();
		}
		//Log path
		Utility.instance().addLog("Calculating path from [" + Start.x + "," + Start.y + "] to [" + m_Labyrinth.getExit().x + "," + m_Labyrinth.getExit().y + "]...");

		//Get path to exit
		Point[] ExitPath = Algorithm.getPath(m_Labyrinth, Start, m_Labyrinth.getExit());
		m_Path.addAll(Arrays.asList(ExitPath));

		//Transform to origin
		/*Point Offset = new Point(m_Labyrinth.getEntry());
		for (int i = 0; i < m_Path.size(); i++) {
			m_Path.elementAt(i).x -= Offset.x;
			m_Path.elementAt(i).y -= Offset.y;
		}*/
	}

	public String getPath() {
		//Initialize variable
		String Path = "";

		//If path exist
		if (m_Path != null) {
			//For each point
			for (int i = 0; i < m_Path.size(); i++) {
				//Add to the path
				Path += String.valueOf(m_Path.elementAt(i).x) + ",";
				Path += String.valueOf(m_Path.elementAt(i).y) + ";";
			}
		}
		
		//Return path
		return  Path;
	}

	//
	protected Labyrinth		m_Labyrinth;
	protected Vector<Point>	m_Path;

}
